﻿var treeEditHandler = function (treeID) {
    var me = this;
    var jqTree;
    var hasInit = false;

    this.contentIframeID = undefined;
    this.treePanelID = undefined;
    this.menuID = undefined;
    this.menuCollapseID = undefined;
    this.menuExpandID = undefined;
    this.formID = undefined;
    this.formName = undefined;
    this.childFormID = undefined;
    this.childFormName = undefined;

    // 自定义菜单显示接口 有两个参数node 和 menu对象
    this.iOnMenuShow = undefined;

    // 自定义节点拖入之前事件 有两个参数target, source
    this.iOnBeforeDrop = undefined;

    // 加载成功后事件，参数node, data
    this.iOnLoadSuccess = undefined;

    // 刪除成功后事件，参数node
    this.iOnDelete = undefined;

    // 自定义双击节点接口 有一个参数node
    this.iOnNodeDblClick = function (node) {
        if (me.getParentNode(node) == null) {
            $.messager.alert('提示', "不允许选择根节点，请重新选择，或者取消选择！", "error");
            return false;
        }
    };

    // 给布局区域的表头添加工具栏
    function easyuiAddToolbar(regionID, toolManuID, initHidden) {
        var toolContainer = $('#' + regionID).prev().find(".tool-container");
        if (toolContainer.length <= 0) {
            var toolTitle = $('#' + regionID).prev().find(".panel-tool");
            toolContainer = $("<div id=\"" + regionID + "_toolContainer\" class=\"tool-container\" style=\"float:left\"></div>");
            toolTitle.prepend(toolContainer);
            if (initHidden) {
                toolContainer.hide();
            }
        }
        var toolLink = $('#' + toolManuID).prependTo(toolContainer);
        $('#' + toolManuID).attr("style", "font-size: 12px; font-weight:normal; color: Black;text-decoration: none; float:right");
    }

    this.bindEditor = function () {
        jqTree = $("#" + treeID);

        jqTree.tree({
            onLoadSuccess: me.eventLoadSuccess,
            onLoadError: me.eventLoadError,
            formatter: me.formatterNode
        });

        me.bindNodeSelect();
        me.bindDragAndDrop();
        me.bindNodeDblClick();
    };

    function usageSingleSelection() {
        var exUsageType = jqTree.attr('exUsageType');
        if (exUsageType == 'SingleSelection'
            || usageSingleReferCopy(jqTree)
            || usageSingleListFilter(jqTree)) {
            return true;
        }
        return false;
    };

    function usageSingleReferCopy(jqTree) {
        var exUsageType = jqTree.attr('exUsageType');
        if (exUsageType == 'SingleReferCopy') {
            return true;
        }
        return false;
    }

    function usageSingleListFilter(jqTree) {
        var exUsageType = jqTree.attr('exUsageType');
        if (exUsageType == 'SingleListFilter') {
            return true;
        }
        return false;
    }

    function parentShowNewDialogByRefer(node) {
        if (top.getLastLayer) {
            var lastLayer = top.getLastLayer();
            if (lastLayer && lastLayer.showNewDialogByRefer) {
                lastLayer.showNewDialogByRefer({ _ID: node.id });
            }
        }
    }

    this.formatterNode = function (node) {
        var text = node.text;
        if (node.attributes && node.attributes._ChildRecordCount != null) {
            text = text + '<span title="统计' + me.childFormName + '数量" style="color:blue">(' + node.attributes._ChildRecordCount + ')</span>';
        }
        return text;
    };

    this.getNewContentUrl = function (nodeID) {
        return '/Business/FormData/NewPage?FormID=' + me.childFormID + '&ParentID=' + nodeID;
    };

    this.getNodeUrl = function (nodeID) {
        return "/Business/ListData/ListPage?FormID=" + me.childFormID + "&parentTableRecordID=" + nodeID;
    };

    this.eventNodeSelect = function (node) {
        if (node && node.id != undefined && me.contentIframeID) {
            $("#" + me.contentIframeID).attr("src", me.getNodeUrl(node.id));
        }
    };

    this.bindToolbarMenu = function () {
        if (me.menuCollapseID != undefined
            && me.menuExpandID != undefined
            && me.treePanelID != undefined) {

            $("#" + me.menuCollapseID).click(me.eventCollapseAll);
            $("#" + me.menuExpandID).click(me.eventExpandAll);

            easyuiAddToolbar(me.treePanelID, me.menuCollapseID);
            easyuiAddToolbar(me.treePanelID, me.menuExpandID);
        }
    };

    this.getOrderUrl = function (sourceID, targetID, isPutTop) {
        if (me.formID > 0) {
            return "/api/FormData/Order/" + sourceID + "?FormID=" + me.formID + "&TargetNodeID=" + targetID + "&IsPutTop=" + isPutTop;
        } else {
            return null;
        }
    };

    this.getParentNode = function (node) {
        return jqTree.tree('getParent', node.target);
    }

    this.enableDragAndDrop = function () {
        jqTree.tree('options').dnd = true;
    };

    this.bindDragAndDrop = function () {
        if (!usageSingleSelection()) {
            me.enableDragAndDrop();

            // 只允许在当前父节点下面平级拖拽
            jqTree.tree('options').onDragEnter = function (target, source) {
                if (!target || !source) {
                    return false;
                }

                var targetNode = jqTree.tree('getNode', target);
                var parentNode = me.getParentNode(source);

                if (!targetNode || !parentNode || parentNode.id == undefined) {
                    return false;
                }

                var targetParentNode = me.getParentNode(targetNode);
                if (!targetParentNode || parentNode.id != targetParentNode.id) {
                    return false;
                }
            };

            // 不允许拖拽到兄弟节点里面去
            jqTree.tree('options').onBeforeDrop = function (target, source, point) {
                if (point == 'append') {
                    return false;
                }
                if (me.iOnBeforeDrop) {
                    me.iOnBeforeDrop(target, source);
                }
            }

            jqTree.tree('options').onDrop = function (target, source, point) {
                var targetNode = jqTree.tree('getNode', target);
                if (!targetNode || me.getParentNode(targetNode) == null) {
                    return;
                }

                var isPutTop = false;
                if (point == 'top') {
                    isPutTop = true;
                }

                var url = me.getOrderUrl ? me.getOrderUrl(source.id, targetNode.id, isPutTop) : null;
                if (url) {
                    $.ajax({
                        type: "POST",
                        url: url
                    })
                    .success(function (result) {
                        if (!(result > 0)) {
                            $.messager.alert('提示', result, "error");
                        }
                    })
                    .error(function (result) {
                        $.messager.alert('提示', result.responseText, "error");
                    });
                }
            };
        }
    };

    this.bindNodeSelect = function (isBind) {
        if (!usageSingleSelection()) {
            if (isBind == false) {
                jqTree.tree('options').onSelect = function () { };
            }
            else {
                jqTree.tree('options').onSelect = me.eventNodeSelect;
            }
        }
    };

    this.bindNodeDblClick = function () {
        if (usageSingleSelection()) {
            jqTree.tree('options').onDblClick = function (node) {
                var lastLayer;
                if (top.getLastLayer) {
                    lastLayer = top.getLastLayer();
                }

                if (usageSingleReferCopy(jqTree)) {
                    parentShowNewDialogByRefer(node);
                }
                else if (node && lastLayer && lastLayer.updatePopupSelectValue) {
                    if (me.iOnNodeDblClick && me.iOnNodeDblClick(node) != false) {
                        var id = node.id;
                        if (!isNaN(id) && id < 0) {
                            id = id * -1;
                        }
                        var nodeData = { "_ID": id, "SystemName": node.text };
                        var selectedNodes = [nodeData];
                        lastLayer.updatePopupSelectValue(selectedNodes,null,false);
                    }
                }
            };
        }
    };

    this.eventCollapseAll = function () {
        jqTree.tree('collapseAll');
    };

    this.eventExpandAll = function () {
        jqTree.tree('expandAll');
    };

    this.eventReload = function () {
        jqTree.tree('reload');
    }

    this.eventLoadSuccess = function (node, data) {

        if (hasInit == false) {
            var root = jqTree.tree("getRoot");
            if (root && root.target) {
                hasInit = true;

                if (usageSingleSelection()) {
                    // 若用于选择界面，首次加载成功时，右侧显示所有子表数据
                    me.eventNodeSelect(root);
                }
                else {
                    // 若用于编辑界面，首次加载成功时，选中根节点
                    jqTree.tree("select", root.target);
                }
            }
        }

        if (me.iOnLoadSuccess) {
            me.iOnLoadSuccess(node, data);
        }
    };

    this.eventLoadError = function (result) {
        var message = "很抱歉，操作出现异常！请联系管理员。";
        if (result) {
            if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                message = result.responseJSON.ExceptionMessage;
            }
            else if (result.responseText) {
                message = result.responseText;
            }
        }

        document.write(message);
    };

    this.beforeShowMenu = undefined;

    this.eventContextMenu = function (e, node) {
        if (usageSingleSelection()) {
            return;
        }


        e.preventDefault();

        var jqMenu = $("#" + me.menuID);
        if (me.beforeShowMenu && typeof (me.beforeShowMenu) == "function") {
            me.beforeShowMenu(jqMenu, node);
        }

        jqMenu.find("#actionDelete").show();
        jqMenu.find("#actionNew").show();
        jqMenu.find("#actionEdit").show();

        // 不允许删除有子项的节点
        var children = undefined;
        try {
            children = jqTree.tree('getChildren', node.target);
        }
        catch (ex) {
            children = undefined;
        }

        if (children && children.length > 0) {
            jqMenu.find("#actionDelete").hide();
        }
        // 不允许删除和修改根节点,根节点只允许有一个子节点
        if (!node || me.getParentNode(node) == null) {
            jqMenu.find("#actionNew").hide();

            jqMenu.find("#actionDelete").hide();
            jqMenu.find("#actionEdit").hide();
        }
        else {

            // 不允许删除或新建内容，对于系统限制节点
            if (node.attributes && node.attributes._IsSystem) {
                jqMenu.find("#actionDelete").hide();
                jqMenu.find("#actionNew").hide();
            }
        }

        // 没有url方法的就隐藏掉
        if (me.getNewContentUrl == null) {
            jqMenu.find("#actionNewContent").hide();
        }
        if (me.getNewUrl == null) {
            jqMenu.find("#actionNew").hide();
        }
        if (me.getEditUrl == null) {
            jqMenu.find("#actionEdit").hide();
        }
        if (me.getDeleteUrl == null) {
            jqMenu.find("#actionDelete").hide();
        }

        // 调用自定义接口
        if (me.iOnMenuShow) {
            me.iOnMenuShow(jqMenu, node);
        }

        me.bindNodeSelect(false);
        jqTree.tree('select', node.target);
        me.bindNodeSelect();

        jqMenu.menu('show', { left: e.pageX, top: e.pageY });
    };

    this.showNewContentForm = function () {
        var node = jqTree.tree('getSelected');
        if (node && node.id != undefined) {
            var url = me.getNewContentUrl(node.id);
            window.showBusinessForm("新建" + me.childFormName, url);
        }
    };

    this.getNewUrl = function (id) {
        return '/Business/FormData/NewPage?FormID=' + me.formID + '&ParentID=' + id;
    };

    this.showNewDialog = function () {
        var node = jqTree.tree('getSelected');
        if (node && node.id != undefined) {
            var url = me.getNewUrl(node.id);
            window.showBusinessForm("新建" + me.formName, url);
        }
    };

    this.getEditUrl = function (id) {
        return '/Business/FormData/EditPage/' + id + '?FormID=' + me.formID;
    };

    this.showEditDialog = function () {
        var node = jqTree.tree('getSelected');
        if (node && node.id != null) {
            var url = me.getEditUrl(node.id);
            window.showBusinessForm("编辑" + me.formName, url);
        }
    };

    this.getDeleteUrl = function (id) {
        return '/api/FormData/Del/' + id + '?FormID=' + me.formID;
    };

    this.showDeleteDialog = function () {
        var node = jqTree.tree('getSelected');
        if (node && node.id != null) {
            $.messager.confirm('删除确认', '确实要删除该记录？', function (r) {
                if (r) {
                    $.ajax({
                        type: "POST",
                        url: me.getDeleteUrl(node.id)
                    })
                    .success(function (result) {
                        if (result > 0) {
                            me.eventReload();

                            if (me.iOnDelete) {
                                me.iOnDelete(node);
                            }
                        }
                        else if (result == -2) {
                            $.messager.alert('提示', "有其他资料引用该数据，禁止删除！", "error");
                        }
                        else {
                            $.messager.alert('提示', "很抱歉，操作出现异常！请联系管理员。", "error");
                        }
                    })
                    .error(function (result) {
                        var message = "很抱歉，操作出现异常！请联系管理员。";
                        if (result) {
                            if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                                message = result.responseJSON.ExceptionMessage;
                            }
                            else if (result.responseText) {
                                message = result.responseText;
                            }
                        }

                        $.messager.alert('错误', message.replace("-10", ""), 'error');
                    });
                }
            });
        }
    };

    $(function () {
        me.bindEditor();
    });
}